// 数组去重
export function Unique(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (res.indexOf(arr[i]) == -1) {
      res.push(arr[i]);
    }
  }
  return res;
}

// 数组取交集 -- 入参为数组
export function Intersect() {
  let res = [];
  let obj = {};
  for (let i = 0; i < arguments.length; i++) {
    // 获取到传入的参数 arguments[i]
    for (let j = 0; j < arguments[i].length; j++) {
      // 遍历数组
      let str = arguments[i][j];
      if (!obj[str]) {
        obj[str] = 1;
      } else {
        obj[str]++;
        if (obj[str] == arguments.length) {
          // 取交集 -- 每个 arr 都有
          res.push(str);
        }
      }
    }
  }
  return res;
}

// 数组取并集 -- 入参为数组
export function Union() {
  let res = [];
  let obj = {};
  for (let i = 0; i < arguments.length; i++) {
    for (let j = 0; j < arguments[i].length; j++) {
      let str = arguments[i][j];
      if (!obj[str]) {
        obj[str] = 1;
        res.push(str);
      }
    }
  }
  return res;
}

/**
 * 日期转字符串
 * @param fmt
 * @returns
 */
export function setDateFormat() {
  Date.prototype.Format = function (fmt) {
    var o = {
      'M+': this.getMonth() + 1, // 月份
      'd+': this.getDate(), // 日
      'h+': this.getHours(), // 小时
      'm+': this.getMinutes(), // 分
      's+': this.getSeconds(), // 秒
      'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
      S: this.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
      }
    }
    return fmt;
  };
}

/**
 * 日期转年月日
 * @param {String} dateStr 格式 2018-01-01 10:00:00
 * @returns fmt 格式  2019年1月1日
 */
export const formatDateInCN = (dateStr) => {
  if (dateStr) {
    let arr = dateStr.split(/[- : \/]/);
    let timeTmp = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
    let fmt = `${timeTmp.getFullYear()}年${timeTmp.getMonth() + 1}月${timeTmp.getDate()}日`;
    return fmt;
  }
};

//兼容苹果浏览器 date的格式为2018-01-01 10:00:00 || 2018/01/01 10:00:00
export function dateFormat(dateStr, fmt) {
  if (dateStr) {
    let arr = dateStr.split(/[- : \/]/);
    let date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
    return date.Format(fmt);
  }
}

// '1,000.00' -> 1000.00 -- 价格转化
export function removeSeparator(num) {
  if (!num.length) {
    return 0;
  }
  let fixNum;
  let decimal = num.indexOf('.') ? num.substring(num.indexOf('.')) : 0;
  if (decimal - 0 > 0) {
    fixNum = num;
  } else {
    fixNum = num.substring(0, num.indexOf('.'));
  }
  fixNum = fixNum.toString().indexOf(',') !== -1 ? fixNum.toString().replace(/,/gi, '') : fixNum;
  return parseFloat(fixNum);
}

// '1000.00' -> '1,000.00' -- 价格转化
export function addSeparator(str) {
  if (!str) return '0.00';
  let num = parseFloat(str).toFixed(3);
  let s = num.substring(0, num.length - 1);
  return (
    s &&
    s.toString().replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
      return $1 + ',';
    })
  );
}

// 小数减法
export const accSub = (arg1, arg2) => {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
};

// 检查 身份证
export function checkCertId(id) {
  if (!id) {
    return false;
  }
  // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
  let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/;
  let result = reg.test(id);
  if (!result) {
    return false;
  }
  return true;
}
// 3个字以内脱敏第一个字，4—6个字脱敏前两个字，大于6个字脱敏第3—6个字
export function noPassByName(str, type) {
  if (str) {
    let length = str.length;
    if (type == 'phone') {
      // 手机号码130****0000
      return str.substring(0, 3) + '****' + str.substring(length - 4, length);
    }
    if (type == 'certId') {
      // 身份证**************0000
      return '**************' + str.substring(length - 4, length);
    }
    if (str.length <= 3) {
      return '*' + str.substring(1, str.length);
    } else if (str.length > 3 && str.length <= 6) {
      return '**' + str.substring(2, str.length);
    } else if (str.length > 6) {
      return str.substring(0, 2) + '****' + str.substring(6, str.length);
    }
  } else {
    return '';
  }
}
// 判断手机号码格式是否正确以及是否是支持的号段
export function isPhoneAvailable(param) {
  let regex = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  // // 支持13、14（仅145、147）、15、16、17（除170、171）、18、19的号段
  // let regex = /^(13[0-9]{9}|14[5,7][0-9]{8}|15[0-9]{9}|16[0-9]{9}|17[2-9][0-9]{8}|18[0-9]{9}|19[0-9]{9})$/;
  return regex.test(param);
}

export function checkName(name) {
  console.log('checkName name = ' + name);
  let names = name.replace(/\s*/g, ''); //去空格
  console.log('checkName name = ' + names);
  if (!names) {
    return false;
  } else {
    // 姓名仅包含汉字和·
    let reg = /^[\u4e00-\u9fa5·]{1,30}$/i;
    if (!reg.test(names)) {
      return false;
    }
  }
  return true;
}

export function checkEmail(str) {
  let re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
  if (re.test(str)) {
    return true;
  } else {
    return false;
  }
}

// 匹配中文、英文、数字、标点符号、空格换行制表符
export function checkCommonText(str) {
  let reg = /^[\u4e00-\u9fa5\w\s,<.>/?;:'"\[{\]}|\\`~!@#$%^&*()-_=+，《。》、？；：‘“【】”’·！￥……（——）]+$/;
  if (reg.test(str)) {
    return true;
  } else {
    return false;
  }
}

export function confirmEnding(str, target) {
  let strLen = str.length;
  let targetLen = target.length;
  if (str.substring(strLen - targetLen) == target) {
    return true;
  }
  return false;
}

// 获取字符串中key对应的value
export function getValueFromStr(str, key) {
  let results = new RegExp('(^|&)' + key + '=([^&]*)').exec(str);
  if (results) {
    return results[2];
  } else {
    return '';
  }
}

export const formatTime = (date = new Date()) => {
  const d = typeof date === 'object' ? date : new Date(date);
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hour = d.getHours();
  const minute = d.getMinutes();
  const second = d.getSeconds();

  const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : '0' + n;
  };

  return {
    ymd: [year, month, day].map(formatNumber).join('-'),
    ymdhms: [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':'),
  };
};

const ONE_DAY = 24 * 60 * 60 * 1000;

export const getToday = () => {
  return {
    startTime: formatTime().ymd,
    endTime: formatTime().ymd,
  };
};
export const getYesterday = () => {
  const yDate = new Date().getTime() - ONE_DAY;
  return {
    startTime: formatTime(yDate).ymd,
    endTime: formatTime(yDate).ymd,
  };
};
export const getWeek = () => {
  const date = new Date();
  //本周第一天
  const start = ONE_DAY * (date.getDay() === 0 ? 6 : date.getDay() - 1);
  return {
    startTime: formatTime(date.getTime() - start).ymd,
    endTime: formatTime().ymd,
  };
};
export const getMonth = () => {
  const date = new Date();
  const start = date.setDate(1); //本月第一天
  // const end = new Date(date.getFullYear(), date.getMonth() + 1, 0); //本月的最后一天
  return {
    startTime: formatTime(start).ymd,
    endTime: formatTime().ymd,
  };
};

export const formatWeekDay = (index) => {
  let weekMap = {
    0: '周日',
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
  };
  return weekMap[index];
};

// 金额格式化
export const moneyFormat = (str) => {
  if (!str) return '0.00';
  let num = parseFloat(str).toFixed(2);
  return num;
};

// 是否是数字
export function isNumber(val) {
  let reg = /^\d+(\.\d+)?$/;
  return reg.test(val);
}

// 产生随机数
export function getUuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// 三位分节法
export const toQFW = (param) => {
  if (param === 0) {
    return 0;
  } else if (!param) {
    return null;
  } else {
    let str = param.toString();
    return str.replace(/\B(?=(\d{3})+\b)/g, ',');
  }
};

// 【订单状态】过滤器
export const transformStatusStr = (value) => {
  if (value) {
    return value.split('-')[0];
  } else {
    return value;
  }
};

// 验证金额（含零），保留两位小数
export const validAmt = (val) => {
  const reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
  return reg.test(val);
};

// 小数相减
export const subtraction = (arg1, arg2) => {
  let r1, r2, m, n;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = r1 >= r2 ? r1 : r2;
  return +((arg1 * m - arg2 * m) / m).toFixed(n);
};

/**
 * Checks whether a string is a valid Chinese phone number.
 *
 * @param {string} phoneNumber - The phone number to check.
 * @returns {boolean} - `true` if the phone number is valid, `false` otherwise.
 */
export const isMobilePhone = (phoneNumber) => {
  // A valid Chinese phone number should start with "1", followed by 10 digits.
  const phoneNumberRegex = /^1\d{10}$/;
  return phoneNumberRegex.test(phoneNumber + '');
};

export const getMoreDateObj = (num, unit = 'day') => {
  let time = 0;
  switch (unit) {
    case 'day':
      time = 24 * 60 * 60 * 1000;
      break;
    case 'min':
      time = 60 * 1000;
      break;
    case 'hour':
      time = 60 * 60 * 1000;
      break;
    default:
      time = 24 * 60 * 60 * 1000;
      break;
  }

  const currentDate = new Date();
  const futureDate = new Date(currentDate.getTime() + num * time);
  return futureDate;
};
